<?php

abstract class AbstractTWLPageController {

    protected function getSiteTitle() { return Settings::config('system')->get('site', 'site_title'); }

    /**
     * @var AbstractTWLSitePage
     */
    protected $oExecutingPage;

    /**
     * @var TemplateExecutor
     */
    protected $oTemplateExecutor;

    public final function __construct(AbstractTWLSitePage $oExecutingPage) {

        $this->oExecutingPage = $oExecutingPage;

        $this->oTemplateExecutor = new TemplateExecutor(
            Dir::getRoot() . Settings::config('system')->get('pathes', 'web_templates')
        );

        if (!empty($_POST) || !empty($_FILES)) {
            $this->doHandlePostRequest();
        }

        $this->tryHandleAjaxRequest();


        $this->oTemplateExecutor->assignArray(array(
            'SITE_TITLE'   => $this->getSiteTitle(),
            'PAGE_TITLE'   => $this->oExecutingPage->getTitle(),
            'CURRENT_PATH' => Form::getRequestedPath(),
            'HAS_AJAX'     => !$this->getAjaxHandler()->isNull(),
        ));

        $hPagesWithRss = array_flip( Settings::config('system')->getSection('rss') );

        $oUrl = Url::createCurrent();
        $path = $oUrl->getPath();
        $pathWithParams = $oUrl->composeLinkOnSite();

        if (isset($hPagesWithRss[$path])) {
            $this->oTemplateExecutor->assign('RSS_FEED', $hPagesWithRss[$path]);
        } else if (isset($hPagesWithRss[$pathWithParams])) {
            $this->oTemplateExecutor->assign('RSS_FEED', $hPagesWithRss[$pathWithParams]);
        }

        $this->init();
    }

    public function displayPage() {
        Output::htmlHeader();
        $this->doDisplayPage();
    }

    public function displayRss() {

        $oExporter = new RssExporter(Settings::config('system')->get('site', 'encoding'));

        $oExporter->setTitle($cfg->getSiteTitle());
        $oExporter->setDescription($this->oExecutingPage->getTitle());
        $oExporter->setLink($this->getPageUrl());

        Output::rssHeader();
        $this->doDisplayRss($oExporter);
    }

    protected function getPageUrl() {
        return Settings::config('system')->get('site', 'site_url') . $this->oExecutingPage->getUrl();

    }

    protected function tryHandleAjaxRequest() {
        if ($cmd = Form::getStringAnyway('cmd')) {
            $oHandler = $this->getAjaxHandler();
            $oHandler->tryHandleCommand($cmd);
            exit;
        }
    }

    protected function doDisplayPage() {
        echo 'page ' . Form::getRequestedPath();
    }

    protected function doHandlePostRequest() {}

    protected function doDisplayRss(RssExporter $oExporter) {
        throw new Exception('rss not implemented in ' . get_class($this));
    }

    /**
     * @return AbstractAjaxHandler
     */
    protected function getAjaxHandler() { return new NullAjaxHandler(); }

    protected function init() {}
}

?>